
package com.jf.cloud.supplier.controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.jf.cloud.api.auth.bo.UserInfoInTokenBO;
import com.jf.cloud.api.biz.feign.NotifyFeignClient;
import com.jf.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.constant.SendTypeEnum;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.PrincipalUtil;
import com.jf.cloud.supplier.dto.SupplierUserDTO;
import com.jf.cloud.supplier.service.SupplierDetailService;
import com.jf.cloud.supplier.service.SupplierUserService;
import com.jf.cloud.supplier.vo.SupplierUserSimpleVO;
import com.jf.cloud.supplier.vo.SupplierUserVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * @author zz
 * @date 2020/09/02
 */
@RequestMapping(value = "/s/supplier_user")
@RestController
@Tag(name = "店铺用户信息")
public class SupplierUserController {

    @Value("${jfcloud.expose.operation.auth:}")
    private Boolean permission;
    @Autowired
    private SupplierUserService supplierUserService;

    @Autowired
    private SupplierDetailService supplierDetailService;

    @Autowired
    private NotifyFeignClient notifyFeignClient;

    @GetMapping("/info")
    @Operation(summary = "登陆店铺用户信息" , description = "获取当前登陆店铺用户的用户信息")
    public ServerResponseEntity<SupplierUserSimpleVO> info() {
        UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get();
        SupplierUserSimpleVO supplierUserSimple = new SupplierUserSimpleVO();
        supplierUserSimple.setIsAdmin(userInfoInTokenBO.getIsAdmin());
        supplierUserSimple.setUserName(userInfoInTokenBO.getUserName());
        if (!Objects.equals(userInfoInTokenBO.getTenantId(), Constant.DEFAULT_SHOP_ID)) {
            SupplierApiDetailVO supplierDetail = supplierDetailService.getBySupplierId(userInfoInTokenBO.getTenantId());
            supplierUserSimple.setAvatar(supplierDetail.getSupplierLogo());
            supplierUserSimple.setSupplierName(supplierDetail.getSupplierName());
        }
        return ServerResponseEntity.success(supplierUserSimple);
    }

    @GetMapping("/page")
    @Operation(summary = "店铺用户列表" , description = "获取店铺用户列表")
    public ServerResponseEntity<PageVO<SupplierUserVO>> page(@Valid PageDTO pageDTO, @ParameterObject SupplierUserDTO supplierUserDTO) {
        UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get();
        supplierUserDTO.setSupplierId(userInfoInTokenBO.getTenantId());
        PageVO<SupplierUserVO> supplierUserPage = supplierUserService.pageBySupplierId(pageDTO, supplierUserDTO);
        return ServerResponseEntity.success(supplierUserPage);
    }

    @GetMapping
    @Operation(summary = "获取店铺用户信息" , description = "根据用户id获取店铺用户信息")
    public ServerResponseEntity<SupplierUserVO> detail(@RequestParam Long supplierUserId) {
        return ServerResponseEntity.success(supplierUserService.getByUserId(supplierUserId));
    }

    @PostMapping
    @Operation(summary = "保存店铺用户信息" , description = "保存店铺用户信息")
    public ServerResponseEntity<Void> save(@Valid @RequestBody SupplierUserDTO supplierUserDTO) {
        if (!PrincipalUtil.isMobile(supplierUserDTO.getPhone())) {
            throw new LuckException("请输入正确格式的手机号!");
        }
        if (StrUtil.isBlank(supplierUserDTO.getValidCode())) {
            throw new LuckException("请输入验证码");
        }
        supplierUserDTO.setSupplierId(AuthUserContext.get().getTenantId());
        checkCode(supplierUserDTO);
        supplierUserService.saveAccount(supplierUserDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新店铺用户信息" , description = "更新店铺用户信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody SupplierUserDTO supplierUserDTO) {
        // 线上的supplier账户资料不可修改
        String userName = "supplier";
        Long supplierId = AuthUserContext.get().getTenantId();
        if (Objects.equals(supplierUserDTO.getUsername(), userName) && Objects.equals(supplierUserDTO.getSupplierId(), supplierId) && BooleanUtil.isFalse(permission)) {
            throw new LuckException("暂无权限修改该用户信息");
        }
        SupplierUserVO dbSupplierUser = supplierUserService.getByUserId(supplierUserDTO.getSupplierUserId());
        if (!Objects.equals(dbSupplierUser.getSupplierId(), supplierId)) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        if (!PrincipalUtil.isMobile(supplierUserDTO.getPhone())) {
            throw new LuckException("请输入正确格式的手机号!");
        }
        // 如果修改了手机号码，就需要校验验证码
        if (!StrUtil.equals(dbSupplierUser.getPhone(), supplierUserDTO.getPhone())) {
            if (StrUtil.isBlank(supplierUserDTO.getValidCode())) {
                throw new LuckException("修改了手机号，请输入验证码校验");
            }
            checkCode(supplierUserDTO);
        }
        supplierUserDTO.setSupplierId(dbSupplierUser.getSupplierId());
        supplierUserService.updateAccount(supplierUserDTO);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除店铺用户信息" , description = "根据店铺用户id删除店铺用户信息")
    public ServerResponseEntity<Void> delete(@RequestParam Long supplierUserId) {
        UserInfoInTokenBO userInfoInToken = AuthUserContext.get();
        SupplierUserVO dbSupplierUser = supplierUserService.getByUserId(supplierUserId);
        if (!Objects.equals(dbSupplierUser.getSupplierId(), userInfoInToken.getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        } else if (Objects.equals(userInfoInToken.getUserId(), supplierUserId)) {
            throw new LuckException("您正在使用当前账号，无法进行删除操作");
        }
        supplierUserService.deleteById(supplierUserId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/verify_account")
    @Operation(summary = "验证店铺账号" , description = "根据用户id获取店铺用户信息")
    public ServerResponseEntity<Boolean> verifyAccount(@ParameterObject SupplierUserDTO supplierUserDTO) {
        // 验证手机号/邮箱/用户名在数据库中是否已经存在
        return supplierUserService.verifySupplierUserAccount(supplierUserDTO);
    }

    /**
     * 校验验证码
     *
     * @param supplierUserDTO
     * @return
     */
    private void checkCode(SupplierUserDTO supplierUserDTO) {
        // 手机号验证码
        String phone = supplierUserDTO.getPhone();
        if (StrUtil.isNotBlank(phone)) {
            ServerResponseEntity<Boolean> sendNotifyResponse = notifyFeignClient.checkValidCode(phone, supplierUserDTO.getValidCode(), SendTypeEnum.VALID);
            Boolean data = sendNotifyResponse.getData();
            if (Objects.equals(sendNotifyResponse.getCode(), ResponseEnum.OK.value()) && Objects.nonNull(data) && !data) {
                throw new LuckException("验证码有误或已过期");
            }
        }
        //邮箱验证码
    }
}
